import * as vscode from 'vscode';
import { BaseI18nHandler } from './base'
import { parse, traverse } from '@babel/core'
import { Words } from '../interfaces/Words'
import { compileToFunctions, compile, parseComponent } from 'vue-template-compiler'
export class VueI18nHandler extends BaseI18nHandler {
    private ast: any;
    constructor(context: vscode.ExtensionContext) {

        super(context)
    }

    /**
    * 获取页面内所有中文词组
    */
    getChineseWords() {

        const { template, script, styles } = parseComponent(this.fileContent)
        let templateASt = this.getTemplateAst(template?.content)
        let jsASt = this.getJavascriptAst(script?.content)


        if (!templateASt && !jsASt) {
            return [];
        }

        return [...this.getChineseWordsByJSAst(jsASt), ...this.getChineseWordsByTemplateAst(templateASt)]

    }
    /**
     * 采集中文内容
     */
    getChineseWordsByJSAst(ast) {
        const words: Words[] = [];
        traverse(ast, {
            ["StringLiteral"]: (path) => {
                console.log(path.node.value);
                if (/[\u4e00-\u9fa5]/.test(path.node.value)) {
                    words.push({
                        value: path.node.value,
                        loc: path.node.loc,
                        isJsxAttr: path.parent.type === "JSXAttribute",
                        // id: getId(),
                    });
                }
            }, ["TemplateElement"]: (path) => {
                console.log('-----------------');
                console.log(path.node.value);
                if (/[\u4e00-\u9fa5]/.test(path.node.value.raw)) {

                }
            }
        })
        return words;
    }
    getChineseWordsByTemplateAst(node) {
        const chineseArray = [];
        // 纯文本
        if (node.type == 3 && node.text.trim()) {
            chineseArray.push(
                {
                    value: node.text.trim(),
                    loc: '',
                    isJsxAttr: false,
                    // id: getId(),
                }
            )
        }
        // 文本加参数
        else if (node.type == 2) {
            node.tokens.forEach(item => {
                if (typeof item == 'string' && item.trim()) {
                    chineseArray.push(
                        {
                            value: item.trim(),
                            loc: '',
                            isJsxAttr: false,
                            // id: getId(),
                        }
                    )
                }
            })

        }
        if (node.children) {
            node.children.forEach(item => {
                traverse(item)
            });
        }
        return chineseArray;
    }
    /**
    * 获取AST
    */
    getTemplateAst(template: string) {
        return compile(template, {}).ast
    }

    getJavascriptAst(script: string) {
        return parse(script, { sourceType: 'module' });
    }



}